package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"ykone/models/mysql"

	"ykone/ykonerpc/internal/svc"
	"ykone/ykonerpc/ykonerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProduceAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProduceAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProduceAddLogic {
	return &ProduceAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProduceAddLogic) ProduceAdd(in *ykonerpc.ProduceAddRequest) (*ykonerpc.ProduceAddResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Model(&user).Where("product_name  = ?", in.ProductName).Find(&user)

	if user.ID != 0 {
		return nil, fmt.Errorf("商品已经存在,请重新添加")
	}

	produceadd := mysql.Produce{
		Model:        gorm.Model{},
		ProductName:  in.ProductName,
		ProductStore: in.ProductStore,
		Price:        in.Price,
		Img:          in.Img,
		UserId:       int(in.UserID),
	}

	err := mysql.DB.Debug().Model(&produceadd).Create(&produceadd).Error

	if err != nil {
		return nil, fmt.Errorf("商品添加失败")
	}

	return &ykonerpc.ProduceAddResponse{Id: int64(produceadd.UserId)}, nil
}
